package com.junzhiit.nengji.dao.impl;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.bainaeco.framework.base.dao.AbstractBaseDAO;
import com.bainaeco.framework.common.jdbc.StatementParameter;
import com.bainaeco.framework.enums.IsDelete;
import com.junzhiit.nengji.bo.AreaBO;
import com.junzhiit.nengji.dao.AreaDAO;
import com.junzhiit.nengji.model.Area;
import com.junzhiit.nengji.model.enums.AreaLevel;

@Repository
public class AreaDAOImpl extends AbstractBaseDAO<Area> implements AreaDAO {
	
	@Override
	public List<Area> findInfo(Area area){
		StatementParameter param=new StatementParameter();
		StringBuffer sql=new StringBuffer();
		sql.append(" select * from area");
		sql.append(" where 1=1");
		
		if(area.getLevel()!=null){
			sql.append(" and `level`=?");
			param.setInt(area.getLevel());
		}
		if(area.getParentId()!=null){
			sql.append(" and parent_id=?");
			param.setInt(area.getParentId());
		}
		
		return queryForList(sql.toString(),Area.class, param);
	}

	@Override
	public List<AreaBO> getArea() {
		StatementParameter param=new StatementParameter();
		StringBuffer sql=new StringBuffer();
		
		sql.append("select p.*,");
		sql.append("(select count(*)");
		sql.append(" from area c");
		sql.append(" where c.is_delete=? and c.parent_id=p.city_id)'childrenCount'");
		sql.append(" from area p");
		sql.append(" where p.is_delete=? and p.level in(?,?)");
		param.setInt(IsDelete.NO.toIntValue());
		param.setInt(IsDelete.NO.toIntValue());
		param.setInt(AreaLevel.ZERO.toIntValue());
		param.setInt(AreaLevel.ONE.toIntValue());
		
		return queryForList(sql.toString(),AreaBO.class, param);
	}
	
	@Override
	public List<Area> findByIds(String[] ids) {
		StatementParameter param = new StatementParameter();
		StringBuilder sql = new StringBuilder();
		
		sql.append("select * from area ");
		sql.append("where id in ( ");
		for (int i= 0;i < ids.length; i++) {
			switch (i) {
			case 0:
				sql.append("?");
				break;
			default:
				sql.append(", ?");
				break;
			}
			param.setString(ids[i]);
		}
		sql.append(") order by level asc");
		
		return queryForList(sql.toString(), Area.class, param);
	
	}
	
	@Override
	public List<Area> findAll(){
		StringBuffer sql=new StringBuffer();
		sql.append(" select id,name,parent_id,city_id,level from area");
		return super.queryForList(sql.toString(), Area.class);
	}
}
